<template>
  <div class="transactions-container">
    <div class="transactions-header">
      <h1>交易记录</h1>
      <div class="header-actions">
        <InputSearch 
          v-model:value="searchKeyword"
          placeholder="搜索交易记录"
          class="search-input"
          :maxlength="50"
        />
        <Button type="primary" @click="showAddModal = true">
          <IconPlus class="mr-2" />
          添加交易
        </Button>
      </div>
    </div>
    
    <!-- 筛选和统计 -->
    <div class="filter-section">
      <div class="filter-controls">
        <Select v-model:value="filterType" placeholder="选择类型" class="filter-select">
          <SelectOption value="">全部类型</SelectOption>
          <SelectOption value="income">收入</SelectOption>
          <SelectOption value="expense">支出</SelectOption>
        </Select>
        
        <Select v-model:value="filterCategory" placeholder="选择分类" class="filter-select">
          <SelectOption value="">全部分类</SelectOption>
          <template v-for="category in filteredCategories" :key="category.id">
            <SelectOption :value="category.id">{{ category.name }}</SelectOption>
          </template>
        </Select>
        
        <DatePicker 
          v-model:value="dateRange" 
          type="range"
          placeholder="选择日期范围"
          class="filter-datepicker"
        />
      </div>
      
      <div class="filter-stats">
        <span class="stat-item">
          <span class="stat-label">筛选结果：</span>
          <span class="stat-value">{{ filteredTransactions.length }}</span>
          <span class="stat-unit">条</span>
        </span>
        <span class="stat-item">
          <span class="stat-label">收入：</span>
          <span class="stat-value income">{{ formatCurrency(filteredIncome) }}</span>
        </span>
        <span class="stat-item">
          <span class="stat-label">支出：</span>
          <span class="stat-value expense">{{ formatCurrency(filteredExpense) }}</span>
        </span>
      </div>
    </div>
    
    <!-- 交易列表 -->
    <div class="transactions-table">
      <Table 
        :columns="columns" 
        :data="filteredTransactions"
        :pagination="pagination"
        :loading="loading"
        class="transaction-table"
      >
        <template #cell(category)="{ record }">
          <span>{{ getCategoryName(record.category) }}</span>
        </template>
        <template #cell(amount)="{ record }">
          <span :class="record.type === 'income' ? 'income' : 'expense'">
            {{ record.type === 'income' ? '+' : '-' }}{{ formatCurrency(record.amount) }}
          </span>
        </template>
        <template #cell(actions)="{ record }">
          <Space>
            <Button 
              size="small" 
              type="text" 
              @click="handleEdit(record)"
              icon="icon-edit"
            >
              编辑
            </Button>
            <Button 
              size="small" 
              type="text" 
              danger
              @click="handleDelete(record.id)"
              icon="icon-delete"
            >
              删除
            </Button>
          </Space>
        </template>
      </Table>
    </div>
    
    <!-- 添加交易模态框 -->
    <Modal 
      v-model:visible="showAddModal" 
      title="添加交易记录" 
      @ok="handleAddTransaction"
      @cancel="handleCancelAdd"
    >
      <div class="modal-form">
        <Form v-model:model="newTransaction" :rules="transactionRules" ref="addFormRef">
          <FormItem label="交易类型" field="type">
            <RadioGroup v-model:value="newTransaction.type">
              <Radio value="income">收入</Radio>
              <Radio value="expense">支出</Radio>
            </RadioGroup>
          </FormItem>
          
          <FormItem label="交易分类" field="category">
            <Select v-model:value="newTransaction.category" placeholder="选择分类">
              <template v-for="category in getCategoriesByType(newTransaction.type)" :key="category.id">
                <SelectOption :value="category.id">{{ category.name }}</SelectOption>
              </template>
            </Select>
          </FormItem>
          
          <FormItem label="交易金额" field="amount">
            <InputNumber 
              v-model:value="newTransaction.amount" 
              placeholder="请输入金额"
              :min="0.01"
              :step="0.01"
              style="width: 100%"
            />
          </FormItem>
          
          <FormItem label="交易日期" field="date">
            <DatePicker 
              v-model:value="newTransaction.date" 
              placeholder="选择日期"
              style="width: 100%"
            />
          </FormItem>
          
          <FormItem label="交易描述" field="description">
            <Input 
              v-model:value="newTransaction.description" 
              placeholder="请输入交易描述"
              type="textarea"
              :maxlength="200"
              show-word-limit
            />
          </FormItem>
        </Form>
      </div>
    </Modal>
    
    <!-- 编辑交易模态框 -->
    <Modal 
      v-model:visible="showEditModal" 
      title="编辑交易记录" 
      @ok="handleUpdateTransaction"
      @cancel="handleCancelEdit"
    >
      <div class="modal-form">
        <Form v-model:model="editTransaction" :rules="transactionRules" ref="editFormRef">
          <FormItem label="交易类型" field="type">
            <RadioGroup v-model:value="editTransaction.type">
              <Radio value="income">收入</Radio>
              <Radio value="expense">支出</Radio>
            </RadioGroup>
          </FormItem>
          
          <FormItem label="交易分类" field="category">
            <Select v-model:value="editTransaction.category" placeholder="选择分类">
              <template v-for="category in getCategoriesByType(editTransaction.type)" :key="category.id">
                <SelectOption :value="category.id">{{ category.name }}</SelectOption>
              </template>
            </Select>
          </FormItem>
          
          <FormItem label="交易金额" field="amount">
            <InputNumber 
              v-model:value="editTransaction.amount" 
              placeholder="请输入金额"
              :min="0.01"
              :step="0.01"
              style="width: 100%"
            />
          </FormItem>
          
          <FormItem label="交易日期" field="date">
            <DatePicker 
              v-model:value="editTransaction.date" 
              placeholder="选择日期"
              style="width: 100%"
            />
          </FormItem>
          
          <FormItem label="交易描述" field="description">
            <Input 
              v-model:value="editTransaction.description" 
              placeholder="请输入交易描述"
              type="textarea"
              :maxlength="200"
              show-word-limit
            />
          </FormItem>
        </Form>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useFinanceStore, type Transaction } from '../store/finance';
import { 
  Table, 
  InputSearch, 
  Button, 
  Modal, 
  Form, 
  FormItem, 
  RadioGroup, 
  Radio, 
  Select, 
  InputNumber, 
  DatePicker, 
  Input, 
  Space 
} from '@arco-design/web-vue';
import { IconPlus } from '@arco-design/web-vue/es/icon';

const financeStore = useFinanceStore();

// 状态管理
const searchKeyword = ref('');
const filterType = ref('');
const filterCategory = ref('');
const dateRange = ref<string[]>([]);
const showAddModal = ref(false);
const showEditModal = ref(false);
const loading = ref(false);
const addFormRef = ref<Form>();
const editFormRef = ref<Form>();
const currentEditId = ref<string>('');

// 表单数据
const newTransaction = ref<Omit<Transaction, 'id'>>({
  type: 'expense',
  category: '',
  amount: 0,
  date: new Date().toISOString().split('T')[0],
  description: ''
});

const editTransaction = ref<Transaction>({
  id: '',
  type: 'expense',
  category: '',
  amount: 0,
  date: '',
  description: ''
});

// 表单验证规则
const transactionRules = {
  type: [{
    required: true,
    message: '请选择交易类型',
    trigger: 'change'
  }],
  category: [{
    required: true,
    message: '请选择交易分类',
    trigger: 'change'
  }],
  amount: [{
    required: true,
    message: '请输入交易金额',
    trigger: 'change'
  }, {
    type: 'number',
    min: 0.01,
    message: '金额必须大于0',
    trigger: 'change'
  }],
  date: [{
    required: true,
    message: '请选择交易日期',
    trigger: 'change'
  }]
};

// 表格列配置
const columns = [
  {
    title: '交易类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
    render: (type: string) => type === 'income' ? '收入' : '支出'
  },
  {
    title: '交易分类',
    dataIndex: 'category',
    key: 'category',
    width: 120
  },
  {
    title: '交易金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120
  },
  {
    title: '交易日期',
    dataIndex: 'date',
    key: 'date',
    width: 120,
    render: (date: string) => {
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    }
  },
  {
    title: '交易描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right'
  }
];

// 分页配置
const pagination = {
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
};

// 计算属性：根据筛选条件过滤交易记录
const filteredTransactions = computed(() => {
  let transactions = [...financeStore.transactions];
  
  // 按类型筛选
  if (filterType.value) {
    transactions = transactions.filter(t => t.type === filterType.value);
  }
  
  // 按分类筛选
  if (filterCategory.value) {
    transactions = transactions.filter(t => t.category === filterCategory.value);
  }
  
  // 按日期范围筛选
  if (dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0]);
    const endDate = new Date(dateRange.value[1]);
    transactions = transactions.filter(t => {
      const transactionDate = new Date(t.date);
      return transactionDate >= startDate && transactionDate <= endDate;
    });
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    transactions = transactions.filter(t => 
      getCategoryName(t.category).toLowerCase().includes(keyword) ||
      (t.description && t.description.toLowerCase().includes(keyword))
    );
  }
  
  // 按日期排序
  return transactions.sort((a, b) => 
    new Date(b.date).getTime() - new Date(a.date).getTime()
  );
});

// 计算属性：根据类型筛选分类
const filteredCategories = computed(() => {
  if (filterType.value) {
    return financeStore.categories.filter(cat => cat.type === filterType.value);
  }
  return financeStore.categories;
});

// 计算属性：筛选后的收入总额
const filteredIncome = computed(() => {
  return filteredTransactions.value
    .filter(t => t.type === 'income')
    .reduce((sum, t) => sum + t.amount, 0);
});

// 计算属性：筛选后的支出总额
const filteredExpense = computed(() => {
  return filteredTransactions.value
    .filter(t => t.type === 'expense')
    .reduce((sum, t) => sum + t.amount, 0);
});

// 方法：获取分类名称
const getCategoryName = (categoryId: string): string => {
  const category = financeStore.categories.find(cat => cat.id === categoryId);
  return category ? category.name : '未知分类';
};

// 方法：根据类型获取分类
const getCategoriesByType = (type: string) => {
  return financeStore.categories.filter(cat => cat.type === type);
};

// 方法：格式化货币
const formatCurrency = (amount: number): string => {
  return '¥' + amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 方法：处理编辑
const handleEdit = (record: Transaction) => {
  currentEditId.value = record.id;
  editTransaction.value = { ...record };
  showEditModal.value = true;
};

// 方法：处理删除
const handleDelete = (id: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条交易记录吗？',
    onOk: () => {
      financeStore.deleteTransaction(id);
    }
  });
};

// 方法：处理添加交易
const handleAddTransaction = async () => {
  if (addFormRef.value) {
    const valid = await addFormRef.value.validate();
    if (valid) {
      financeStore.addTransaction(newTransaction.value);
      handleCancelAdd();
    }
  }
};

// 方法：处理更新交易
const handleUpdateTransaction = async () => {
  if (editFormRef.value) {
    const valid = await editFormRef.value.validate();
    if (valid) {
      financeStore.updateTransaction(currentEditId.value, editTransaction.value);
      handleCancelEdit();
    }
  }
};

// 方法：取消添加
const handleCancelAdd = () => {
  addFormRef.value?.resetFields();
  newTransaction.value = {
    type: 'expense',
    category: '',
    amount: 0,
    date: new Date().toISOString().split('T')[0],
    description: ''
  };
  showAddModal.value = false;
};

// 方法：取消编辑
const handleCancelEdit = () => {
  editFormRef.value?.resetFields();
  showEditModal.value = false;
};

// 组件挂载时初始化数据
onMounted(() => {
  financeStore.loadFromLocalStorage();
  if (financeStore.transactions.length === 0) {
    financeStore.initMockData();
  }
});
</script>

<style scoped>
.transactions-container {
  padding: 24px;
}

.transactions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.transactions-header h1 {
  font-size: 24px;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-section {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.filter-controls {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-select {
  width: 150px;
}

.filter-datepicker {
  width: 250px;
}

.filter-stats {
  display: flex;
  gap: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-label {
  color: var(--color-text-secondary);
  font-size: 14px;
}

.stat-value {
  font-weight: 600;
  font-size: 16px;
}

.stat-value.income {
  color: var(--color-success);
}

.stat-value.expense {
  color: var(--color-danger);
}

.stat-unit {
  color: var(--color-text-secondary);
  font-size: 14px;
}

.transactions-table {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 16px;
}

.transaction-table :deep(.arco-table-cell) {
  vertical-align: middle;
}

.transaction-table :deep(.arco-table-cell.amount .income) {
  color: var(--color-success);
  font-weight: 600;
}

.transaction-table :deep(.arco-table-cell.amount .expense) {
  color: var(--color-danger);
  font-weight: 600;
}

.modal-form {
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .transactions-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select,
  .filter-datepicker {
    width: 100%;
  }
  
  .filter-stats {
    flex-direction: column;
    gap: 8px;
  }
  
  .transaction-table :deep(.arco-table-fixed-right) {
    display: none;
  }
}
</style>